<template>
  <AuModal
    :key="rowData?.material_id"
    v-model="showDetailModal"
    :title="t('material.modal.title')"
    width="712"
    height="70vh"
    :padding="false"
    @close="close"
    @formChange="handleChange"
    @handleConfirm="formRef.submit()"
  >
    <div class="p-[16px]">
      <AuForm
        ref="formRef"
        :isInline="false"
        :hiddenBtn="true"
        :hasUnfold="false"
        :formData="formData"
        :formList="formList"
        @submit="handleConfirm"
      >
        <template #spec_behind>
          <div class="wrap">
            <div
              v-for="(item, index) in specList"
              :key="index"
              class="flex mt-2 first:mt-0"
            >
              <el-input
                v-model="item.name"
                class="!w-[200px]"
                :placeholder="t('material.modal.spec.placeholder')"
              />
              <vxe-input
                v-model="item.value"
                class="!w-[200px] mx-2"
                :placeholder="t('material.modal.spec.value_placeholder')"
              >
                <template #suffix> g</template>
              </vxe-input>
              <el-button
                v-if="index > 0"
                type="danger"
                plain
                @click="() => specList.splice(index, 1)"
                >{{ t("buttons.delete") }}
              </el-button>
              <el-button
                v-if="index === 0"
                type="primary"
                @click="() => specList.push({ value: '', name: '' })"
                >{{ t("material.modal.spec.add") }}
              </el-button>
            </div>
          </div>
        </template>

        <template #device_type_behind>
          <vxe-checkbox-group v-model="formData.device_t" :strict="false">
            <vxe-checkbox
              :label="DEVICE_TYPE_ENUM.CABINET"
              :content="t(DEVICE_TYPE_TRANS[DEVICE_TYPE_ENUM.CABINET])"
            />
            <vxe-checkbox
              :label="DEVICE_TYPE_ENUM.TEA_POWDER"
              :content="t(DEVICE_TYPE_TRANS[DEVICE_TYPE_ENUM.TEA_POWDER])"
            />
          </vxe-checkbox-group>
        </template>

        <template #barcode_behind>
          <span class="ml-2 text-[--autata-font-gray-color]">{{
            t("material.modal.barcode_tip")
          }}</span>
        </template>
        <template #barcode_before>
          <el-checkbox
            v-model="use_barcode"
            @change="barcodeHandle"
          />&nbsp;&nbsp;
        </template>

        <template #publish_status_behind>
          <vxe-radio-group v-model="publish_status" :disabled="!!rowData?.id">
            <vxe-radio :label="1" :content="t('material.form.status_up')" />
            <vxe-radio :label="0" :content="t('material.form.status_down')" />
          </vxe-radio-group>
        </template>
      </AuForm>
    </div>
  </AuModal>

  <AuModal
    v-model="showTypePopup"
    :title="t('material.modal.new_type')"
    :width="460"
    show-zoom
    :padding="false"
    @handleConfirm="formTypePopRef.submit()"
  >
    <div class="flex justify-center py-[30px]">
      <AuForm
        ref="formTypePopRef"
        :formList="formTypePopList"
        :isInline="false"
        :hiddenBtn="true"
        class="!w-[386px]"
        @submit="handleConfirmForType"
      />
    </div>
  </AuModal>
</template>
<script setup lang="ts">
import {
  ref,
  toRef,
  h,
  watch,
  onBeforeMount,
  onUpdated,
  nextTick,
  computed
} from "vue";
import { MaterialListProp } from "@/api/cabinet/formula";
import { materialUpd, materialAdd } from "@/api/cabinet/material";

import {
  getMaterialTypeList,
  MaterialTypeProp,
  materialTypeAdd
} from "@/api/cabinet/material";
import {
  BaseProps,
  inputProps,
  numberProps,
  selectProps
} from "@/components/AuForm/type";
import { ElButton, ElInput, ElRadio, ElRadioGroup } from "element-plus";
import { AuModal } from "@/components/AuModal";
import { AuForm } from "@/components/AuForm";
import { ACTION_TYPE } from "@/components/AuTable/type";
import { ElMessage } from "element-plus";
import { isArray, isObject, isString, uuid } from "@pureadmin/utils";
import { cloneDeep } from "lodash-unified";
import { getRandomNumber } from "@/utils/tool";
import { useI18n } from "vue-i18n";
import { DEVICE_TYPE_ENUM, DEVICE_TYPE_TRANS } from "@/utils/constants";
import { $t, transformI18n } from "@/plugins/i18n";

const { t } = useI18n();

defineOptions({
  name: "MaterialModal"
});

interface Props {
  modelValue: boolean;
  rowData: MaterialListProp | null;
  activeType: string;
  lastMatRow: any[];
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  rowData: null,
  activeType: ACTION_TYPE.ADD
});

const emit = defineEmits(["update:modelValue", "handleConfirm"]);

const showDetailModal = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  }
});
const formData = ref<Partial<MaterialListProp>>();
const use_barcode = ref(false);
const publish_status = ref(1);

const showTypePopup = ref(false); //新建物料类型

type FormListTuple = [
  inputProps,
  inputProps,
  selectProps,
  BaseProps,
  // BaseProps,
  // BaseProps,
  BaseProps,
  BaseProps,
  inputProps
  // BaseProps
];
const formList = ref<FormListTuple>([
  {
    type: "input",
    label: "material.form.material_code",
    key: "material_id",
    placeholder: "material.form.material_code_placeholder",
    required: true,
    rules: [
      {
        validator: (rule, value, callback) => {
          const numReg = /^[A-Za-z0-9_-]+$/;
          if (value) {
            if (!numReg.test(value)) {
              callback(new Error(t("material.form.material_code_number")));
            }
            callback();
          }
        },
        trigger: "blur"
      }
    ]
  },
  {
    type: "input",
    label: "material.form.name",
    key: "name",
    placeholder: "material.form.name_placeholder",
    required: true
  },
  {
    type: "select",
    label: "material.form.type",
    key: "type_id",
    placeholder: "material.form.type_placeholder",
    valueKey: "id",
    labelKey: "name",
    options: [],
    style: { width: "200px" },
    behindRender: () => {
      return h(
        ElButton,
        {
          type: "primary",
          class: "ml-2",
          onClick(evt) {
            console.log(evt);
            showTypePopup.value = true;
          }
        },
        t("material.modal.add_type")
      );
    }
  },
  // {
  //   type: "vxe-input",
  //   label: "保质期",
  //   key: "overdue_time_input",
  //   inType: "number",
  //   min: 0,
  //   placeholder: "请输入数字",
  //   style: { width: "200px" },
  //   behindRender: () => {
  //     return h(
  //       "span",
  //       {
  //         class: "ml-2"
  //       },
  //       "小时"
  //     );
  //   },
  //   required: true
  // },
  // {
  //   type: "vxe-input",
  //   label: "清洗周期",
  //   key: "clean_time_input",
  //   inType: "number",
  //   min: 0,
  //   placeholder: "请输入数字",
  //   style: { width: "200px" },
  //   behindRender: () => {
  //     return h(
  //       "span",
  //       {
  //         class: "ml-2"
  //       },
  //       "天"
  //     );
  //   },
  //   required: true
  // },
  {
    type: "el-checkbox",
    label: "material.form.device_type",
    key: "device_type",
    slot: true
  },
  {
    type: "input",
    label: "material.form.spec",
    key: "spec",
    slot: true
  },
  // {
  //   type: "el-checkbox",
  //   label: "material.form.scan_code",
  //   compLabel: "",
  //   key: "use_barcode",
  //   placeholder: "material.form.barcode_placeholder",
  //   style: { width: "auto" }
  // },
  {
    type: "input",
    label: "material.form.scan_code",
    key: "barcode",
    placeholder: "material.form.barcode_placeholder",
    style: { width: "auto" }
  },
  {
    type: "input",
    label: "table.note",
    key: "note",
    inType: "textarea",
    rows: 3,
    maxlength: "100",
    showWordLimit: true,
    placeholder: "material.form.note_placeholder"
  }
  // {
  //   type: "bull",
  //   label: "material.form.status",
  //   key: "publish_status",
  //   slot: true
  // }
]);
const formRef = ref();
const formTypePopRef = ref();

const formTypePopList = ref([
  {
    type: "input",
    key: "name",
    label: "material.type.name",
    placeholder: "material.type.name_placeholder",
    required: true
  },
  {
    type: "input",
    key: "note",
    label: "table.note",
    placeholder: "material.type.note_placeholder",
    inType: "textarea"
  }
]);

const specList = ref([{ name: "", value: "" }]);
const close = () => {
  emit("update:modelValue", false);
};

const barcodeHandle = val => {
  formRef.value.setFormProps("barcode", {
    required: val
  });
};

const handleConfirm = (
  data: MaterialListProp & {
    overdue_time_input: number;
    cold_time_input: number;
    clean_time_input: number;
    hiddenDeviceType: boolean;
  }
) => {
  let i = 1;
  for (const item of specList.value) {
    if (item.name && !item.value) {
      ElMessage.warning(t("material.modal.spec_value_required", { index: i }));
      return;
    }
    if (!item.name && item.value) {
      ElMessage.warning(t("material.modal.spec_name_required", { index: i }));
      return;
    }
    i++;
  }
  console.log(specList.value);
  if (data.overdue_time_input) {
    // 保质期
    data.overdue_time = Math.round(data.overdue_time_input * 3600000);
  }
  if (data.cold_time_input) {
    // 冷藏时间
    data.cold_time = Math.round(data.cold_time_input * 3600000);
  }
  if (data.clean_time_input) {
    // 清洗周期
    data.clean_time = Math.round(data.clean_time_input * 86400000);
  }
  data.spec = JSON.stringify(
    specList.value.filter(v => v.name && v.value)
    // .map(v => ({ ...v, value: v.value }))
  );
  const material_config = {};
  data.forced_clean = false;
  material_config["forced_clean"] = data.forced_clean;
  data.material_config = JSON.stringify(material_config);
  data.amount_unit = "g"; //标准量单位
  data.publish_status = publish_status.value; //上下架状态
  data.use_barcode = use_barcode.value; //是否使用条形码
  data.hiddenDeviceType = true; //条形码
  data.device_type = data.device_t?.join(",");

  let api = materialAdd;
  if (props.activeType === "t-add") {
    console.log("add");
    api = materialAdd;
    data.overdue_time = 3600000;
    data.cold_time = 3600000;
    data.clean_time = 86400000;
  } else if (props.activeType === "edit") {
    console.log("edit");
    api = materialUpd;
  }

  api(data).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: data.id
          ? t("material.modal.edit_success")
          : t("material.modal.add_success"),
        type: "success"
      });
      emit("handleConfirm");
    }
  });
};

const handleChange = ({ key, value }: { key: string; value: any }) => {
  console.log("change");
};

const getTypeListForSelect = (typeId?: number) => {
  const params = {};
  getMaterialTypeList(params).then(res => {
    // formPopList.value[2].options = res.data;
    formRef.value.setFormProps("type_id", {
      options: res.data,
      hidden: false
    });
    if (typeId) {
      formRef.value?.setFormData({
        type_id: typeId
      });
    }
    if (formData.value?.material_id) {
      formRef.value?.setFormProps("material_id", {
        disabled: true
      });
    }
  });
};

const initMaterial = () => {
  let def = [{ name: "", value: "" }];
  if (isString(formData.value.spec)) {
    const list = JSON.parse(formData.value.spec);
    specList.value = list.length ? list : def;
  } else if (isArray(formData.value.spec)) {
    const list = formData.value.spec as Array<{ name: string; value: string }>;
    specList.value = list.length ? list : def;
  }
  // const forced_clean = ref(false);
  // if (isString(formData.value.material_config)) {
  //   forced_clean.value = JSON.parse(
  //     formData.value.material_config
  //   ).forced_clean;
  // }

  const material = {
    ...formData.value,
    spec: specList.value
  };
  formData.value.device_t = formData.value?.device_type?.split(",") ?? [];
  publish_status.value = formData.value?.publish_status ?? 1;
  use_barcode.value = formData.value?.use_barcode ?? false;

  console.log(material);
  formRef.value?.setFormData(material);
};

// onUpdated(() => {
//   getTypeListForSelect();
//
//   if (props.activeType === "edit") {
//     initMaterial();
//     console.log(formData.value);
//     nextTick(() => {
//       formRef.value.setFormData(formData.value); //赋值
//     });
//   }
// });

const reset = () => {
  formRef.value?.reset();
  specList.value = [{ name: "", value: "" }];
  // formTypePopRef.value?.resetForm();
};

//保存类物料型
const handleConfirmForType = (data: MaterialTypeProp) => {
  let formData = formTypePopRef.value.getFormData();
  materialTypeAdd(formData).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: t("material.modal.add_type_success"),
        type: "success"
      });
      showTypePopup.value = false;
      getTypeListForSelect(res.data.id);
    }
  });
};

watch(
  () => [showDetailModal.value, props.rowData],
  ([val, row]) => {
    if (val) {
      const rowData = cloneDeep(row) as MaterialListProp;
      getTypeListForSelect();
      // title.value = rowData?.material_id ? "编辑物料" : "新增物料";
      formData.value = rowData?.material_id
        ? rowData
        : {
            ...(rowData ? rowData : {}),
            device_type: "柜式机"
          };
      if (rowData?.material_id) {
        nextTick(() => {
          initMaterial();
        });
      } else {
        nextTick(() => {
          const lastData =
            isArray(props.lastMatRow) && props.lastMatRow.length
              ? props.lastMatRow[0].material_id
              : null;
          let matId = "";
          if (lastData) {
            matId = String(Number(lastData) + 1).padStart(4, "0");
            if (matId.includes("NaN")) {
              matId = "0001";
            }
          } else {
            matId = "0001";
          }
          setTimeout(() => {
            formRef.value.setFormData({ material_id: matId });
          });
        });
      }
    } else {
      reset();
    }
  }
);
watch(
  () => showTypePopup.value,
  val => {
    if (!val) {
      formTypePopRef.value?.reset();
    }
  }
);
</script>
